package com.cyf.util;

import com.alibaba.fastjson.JSONObject;
import com.cyf.wechat.network.bean.GetOpenidReq;
import com.cyf.wechat.network.bean.GetOpenidRsp;
import com.cyf.wechat.network.bean.GetWechatInfoRsp;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信订阅号工具类
 * Created by cage on 2017/4/21.
 */
@Component
public class WeChatSubscriptionUtil {

    private static String ACCESS_TOKEN = "";
    private static String OLD_ACCESS_TOKEN = "";
    private static final String APPID = "wxf1c9bd730ac9a0ce";
    private static final String APPSECRET = "bfa3da3404bb0072b8dce268cc54e863";
    private static final Logger logger = LoggerFactory.getLogger(WeChatSubscriptionUtil.class);
    private static Date lastDate = new Date();

    public void getWeChatAccessToken() {
        Date curDate = new Date();
        if (!"".equals(ACCESS_TOKEN)) {
            if (curDate.getTime() - lastDate.getTime() < 6900){
                logger.info("不刷新access_token");
                return;
            }
        }
        String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + APPSECRET;
        String tokenReturn = HttpsUtil.get(getTokenUrl, null, null);
        AccessTokenRsp accessTokenRsp = null;
        try {
            accessTokenRsp = ObjectMapperUtils.getObjectMapper().readValue(tokenReturn, AccessTokenRsp.class);
        } catch (IOException e) {
            logger.error("获取订阅号的accessToken失败！"+tokenReturn+" : {}", e);
        }
        if (accessTokenRsp != null && accessTokenRsp.getAccess_token() != null && !"".equals(accessTokenRsp.getAccess_token())) {
            if ("".equals(OLD_ACCESS_TOKEN)) {
                OLD_ACCESS_TOKEN = accessTokenRsp.getAccess_token();
            } else {
                OLD_ACCESS_TOKEN = ACCESS_TOKEN;
            }
            ACCESS_TOKEN = accessTokenRsp.getAccess_token();
            lastDate = new Date();
            logger.info("获取订阅号的accessToken成功！{}", ACCESS_TOKEN);
        } else {
            logger.error("获取订阅号的accessToken失败！{}", tokenReturn);
        }
    }

    public GetLastNewsRsp getLastNews() throws Exception {
        if ("".equals(ACCESS_TOKEN)) {
            getWeChatAccessToken();
        }
        if (!"".equals(ACCESS_TOKEN)) {
            LastNewsRsp lastNewsRsp = getLastNews(ACCESS_TOKEN);
            if (lastNewsRsp != null && lastNewsRsp.getErrcode() == 40001 && !"".equals(OLD_ACCESS_TOKEN)) {
                logger.error("获取图文信息失败，重新获取！");
                lastNewsRsp = getLastNews(OLD_ACCESS_TOKEN);
            }
            if (lastNewsRsp == null) {
                logger.error("获取图文信息失败，返回null!");
                GetLastNewsRsp rsp = new GetLastNewsRsp();
                rsp.setTime((int) (DateUtil.parseDate("2017-04-23", "yyyy-MM-dd").getTime()/1000));
                rsp.setPortraitUrl("http://www.cheyifu2016.com/images/dyh.png");
                rsp.setUrl("http://mp.weixin.qq.com/s?__biz=MzI2OTQ0NzIwNw==&mid=100000130&idx=1&sn=9b9574a411d4fd2ad00d6e203d980d93&chksm=6ae178ca5d96f1dc2000600d520e46ebd487c169cdb03ddb21fd3460b06e9b756000582afa15#rd");
                rsp.setPicUrl("http://mmbiz.qpic.cn/mmbiz_jpg/G9dibSQZSR0vjF5mkGy33JaLqyEuasYVw2JFLkLBaKS8YOEcVEkXYeIsjn01xvP3LTrmzib6wN9Qyr06X89pqWnw/0?wx_fmt=jpeg");
                rsp.setAuthor("智慧停车管理平台");
                return rsp;
//                throw new Exception("获取订阅号最新图文信息失败");
            }

            if (lastNewsRsp.getErrcode() == 0) {
                GetLastNewsRsp rsp = new GetLastNewsRsp();
                Item item = lastNewsRsp.getItem().get(0);
                rsp.setTime(item.getUpdate_time());
                NewsItem newsItem = item.getContent().getNews_item().get(0);
                rsp.setPortraitUrl("http://www.cheyifu2016.com/images/dyh.png");
                rsp.setUrl(newsItem.getUrl());
                rsp.setPicUrl(newsItem.getThumb_url());
                rsp.setAuthor("智慧停车管理平台");
                return rsp;
            } else {
                GetLastNewsRsp rsp = new GetLastNewsRsp();
                rsp.setTime((int) (DateUtil.parseDate("2017-04-23", "yyyy-MM-dd").getTime()/1000));
                rsp.setPortraitUrl("http://www.cheyifu2016.com/images/dyh.png");
                rsp.setUrl("http://mp.weixin.qq.com/s?__biz=MzI2OTQ0NzIwNw==&mid=100000130&idx=1&sn=9b9574a411d4fd2ad00d6e203d980d93&chksm=6ae178ca5d96f1dc2000600d520e46ebd487c169cdb03ddb21fd3460b06e9b756000582afa15#rd");
                rsp.setPicUrl("http://mmbiz.qpic.cn/mmbiz_jpg/G9dibSQZSR0vjF5mkGy33JaLqyEuasYVw2JFLkLBaKS8YOEcVEkXYeIsjn01xvP3LTrmzib6wN9Qyr06X89pqWnw/0?wx_fmt=jpeg");
                rsp.setAuthor("智慧停车管理平台");
                return rsp;
                /*logger.error("获取订阅号最新图文信息失败:{}", lastNewsRsp.getErrmsg());
                throw new Exception("获取订阅号最新图文信息失败!");*/
            }
        }
        return new GetLastNewsRsp("智慧停车管理平台", (int) (new Date().getTime() / 1000), "http://www.cheyifu2016.com/images/dyh.png", "http://mp.weixin.qq.com/s?__biz=MzI2OTQ0NzIwNw==&mid=100000130&idx=1&sn=9b9574a411d4fd2ad00d6e203d980d93&chksm=6ae178ca5d96f1dc2000600d520e46ebd487c169cdb03ddb21fd3460b06e9b756000582afa15#rd", "http://mmbiz.qpic.cn/mmbiz_jpg/G9dibSQZSR0vjF5mkGy33JaLqyEuasYVw2JFLkLBaKS8YOEcVEkXYeIsjn01xvP3LTrmzib6wN9Qyr06X89pqWnw/0?wx_fmt=jpeg");
    }

    private LastNewsRsp getLastNews(String accessToken) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + accessToken;
        logger.info(url);
        Map<String, String> map = new HashMap<>();
        map.put("type", "news");
        map.put("offset", "0");
        map.put("count", "1");
        ObjectMapper mapper = ObjectMapperUtils.getObjectMapper();
        String postText = HttpsUtil.post(url, mapper.writeValueAsString(map));
        postText = new String(postText.getBytes(), "utf-8");
//        logger.info("获取订阅号最新图文信息返回：{}", postText);
        return mapper.readValue(postText, LastNewsRsp.class);
    }

    public GetOpenidRsp getOpenid(String code) {
        GetOpenidReq req = new GetOpenidReq(code);
        GetOpenidRsp rsp = null;
        try {
            String url = WXTemplateMessage.ACCREDIT_ACCESSTOKEN_URL + "?appid=" + req.getAppid() + "&secret=" + req.getSecret() + "&code=" + req.getCode() + "&grant_type=" + req.getGrant_type();
            String json = HttpsUtil.get(url);
            rsp = ObjectMapperUtils.getObjectMapper().readValue(json, GetOpenidRsp.class);
        } catch (Exception e) {
            e.printStackTrace();
            //logger.error("获取微信公众号accesstToken异常:{}", e.getMessage());
        }
        return rsp;
    }

    public GetOpenidRsp getOpenidzh(String code) {
        GetOpenidReq req = new GetOpenidReq(code);
        GetOpenidRsp rsp = null;
        try {
            String url = WXTemplateMessage.ACCREDIT_ACCESSTOKEN_URL + "?appid=" +
                    "wxe9aa5c123a959abf" + "&secret=" + "d30b8d1efad41378f801041d77febd5e"
                    + "&code=" + req.getCode() + "&grant_type=" + req.getGrant_type();
            String json = HttpsUtil.get(url);
            rsp = ObjectMapperUtils.getObjectMapper().readValue(json, GetOpenidRsp.class);
        } catch (Exception e) {
            e.printStackTrace();
//            logger.error("获取微信公众号accesstToken异常:{}", e.getMessage());
        }
        return rsp;
    }


    public GetWechatInfoRsp getWechatInfo(String openId) {
        try {
            //获取 ACCESS_TOKEN
            String access_token = getAccessToken();
            String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token +
                    "&openid=" + openId +
                    "&lang=zh_CN";
            String result = HttpsUtil.get(url, null, null);
            logger.info("【微信】获取基本信息：{}", result);
            GetWechatInfoRsp wechatInfoRsp = ObjectMapperUtils.getObjectMapper().readValue(result, GetWechatInfoRsp.class);
            return wechatInfoRsp;
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("微信授权获取用户信息：{}", e.getMessage());
        }
        return null;
    }

    public String getAccessToken() {

        String accessToken = "";
        // String grantType = "client_credential";// 获取access_token填写client_credential
        //String appId ="wxe9aa5c123a959abf";// 第三方用户唯一凭证
        //  String secret = " 89821a1c799bba5eeda39ed42b7fc73d";// 第三方用户唯一凭证密钥，即appsecret
        // 这个url链接地址和参数皆不能变
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=wx832756d16af60c8c&secret=541ae9a46562d2c09b6662a16127e9fc";
        try {
            //获取提交方式
            HttpGet httpGet = new HttpGet(url);
            //获取到httpclient
            HttpClient httpClient = new DefaultHttpClient();
            //发送请求并得到响应
            HttpResponse response = httpClient.execute(httpGet);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //将得到的响应转为String类型  
                String str = EntityUtils.toString(response.getEntity(), "utf-8");
                //字符串转json
                JSONObject jsonObject = JSONObject.parseObject(new String(str));
                logger.error(str);

                //输出access_token
                accessToken = (String) jsonObject.get("access_token");
            }
            //获取sapi_ti
        } catch (Exception e) {
            logger.error("获取access_token发生异常", e.getMessage());
            e.printStackTrace();
        }
        return accessToken;
    }

    public class GetLastNewsRsp {
        private String author;      // 作者
        private int time;           // 发布时间
        private String portraitUrl; // 头像url
        private String url;         // 点击查看url(详情)
        private String picUrl;      // 展示图片url

        public GetLastNewsRsp() {
        }

        public GetLastNewsRsp(String author, int time, String portraitUrl, String url, String picUrl) {
            this.author = author;
            this.time = time;
            this.portraitUrl = portraitUrl;
            this.url = url;
            this.picUrl = picUrl;
        }

        public String getAuthor() {
            return author;
        }

        public void setAuthor(String author) {
            this.author = author;
        }

        public String getPortraitUrl() {
            return portraitUrl;
        }

        public void setPortraitUrl(String portraitUrl) {
            this.portraitUrl = portraitUrl;
        }

        public int getTime() {
            return time;
        }

        public void setTime(int time) {
            this.time = time;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getPicUrl() {
            return picUrl;
        }

        public void setPicUrl(String picUrl) {
            this.picUrl = picUrl;
        }
    }
}


class AccessTokenRsp {
    private int errcode;
    private String errmsg;
    private String access_token;
    private String expires_in;

    public int getErrcode() {
        return errcode;
    }

    public void setErrcode(int errcode) {
        this.errcode = errcode;
    }

    public String getErrmsg() {
        return errmsg;
    }

    public void setErrmsg(String errmsg) {
        this.errmsg = errmsg;
    }

    public String getAccess_token() {
        return access_token;
    }

    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }

    public String getExpires_in() {
        return expires_in;
    }

    public void setExpires_in(String expires_in) {
        this.expires_in = expires_in;
    }
}

class LastNewsRsp {
    private int errcode;
    private String errmsg;
    private int total_count;
    private int item_count;
    private List<Item> item;

    public int getErrcode() {
        return errcode;
    }

    public void setErrcode(int errcode) {
        this.errcode = errcode;
    }

    public String getErrmsg() {
        return errmsg;
    }

    public void setErrmsg(String errmsg) {
        this.errmsg = errmsg;
    }

    public List<Item> getItem() {
        return item;
    }

    public void setItem(List<Item> item) {
        this.item = item;
    }

    public int getTotal_count() {
        return total_count;
    }

    public void setTotal_count(int total_count) {
        this.total_count = total_count;
    }

    public int getItem_count() {
        return item_count;
    }

    public void setItem_count(int item_count) {
        this.item_count = item_count;
    }
}

class Item {
    private String media_id;
    private Content content;
    private int update_time;

    public String getMedia_id() {
        return media_id;
    }

    public void setMedia_id(String media_id) {
        this.media_id = media_id;
    }

    public Content getContent() {
        return content;
    }

    public void setContent(Content content) {
        this.content = content;
    }

    public int getUpdate_time() {
        return update_time;
    }

    public void setUpdate_time(int update_time) {
        this.update_time = update_time;
    }
}

class Content {
    private List<NewsItem> news_item;
    private int create_time;
    private int update_time;

    public List<NewsItem> getNews_item() {
        return news_item;
    }

    public void setNews_item(List<NewsItem> news_item) {
        this.news_item = news_item;
    }

    public int getCreate_time() {
        return create_time;
    }

    public void setCreate_time(int create_time) {
        this.create_time = create_time;
    }

    public int getUpdate_time() {
        return update_time;
    }

    public void setUpdate_time(int update_time) {
        this.update_time = update_time;
    }
}

class NewsItem {
    private String title;
    private String author;
    private String digest;
    private String content;
    private String content_source_url;
    private String thumb_media_id;
    private int show_cover_pic;
    private String url;
    private String thumb_url;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getDigest() {
        return digest;
    }

    public void setDigest(String digest) {
        this.digest = digest;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getContent_source_url() {
        return content_source_url;
    }

    public void setContent_source_url(String content_source_url) {
        this.content_source_url = content_source_url;
    }

    public String getThumb_media_id() {
        return thumb_media_id;
    }

    public void setThumb_media_id(String thumb_media_id) {
        this.thumb_media_id = thumb_media_id;
    }

    public int getShow_cover_pic() {
        return show_cover_pic;
    }

    public void setShow_cover_pic(int show_cover_pic) {
        this.show_cover_pic = show_cover_pic;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getThumb_url() {
        return thumb_url;
    }

    public void setThumb_url(String thumb_url) {
        this.thumb_url = thumb_url;
    }
}